package com.palm.hubo2o.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

import com.palm.hubo2o.BaseActivity;
import com.palm.hubo2o.R;
import com.palm.hubo2o.model.LoginData;
import com.palm.hubo2o.model.User;
import com.palm.hubo2o.network.PalmCallBack;
import com.palm.hubo2o.network.PalmRetrofit;
import com.palm.hubo2o.network.PalmSession;
import com.palm.hubo2o.network.Request;
import com.palm.hubo2o.network.Result;
import com.palm.hubo2o.view.ProgressDialogCompat;
import com.palm.palmutils.MD5;
import com.palm.palmutils.Settings;
import com.palm.palmutils.StringUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * A login screen that offers login via phone/password.
 */
public class LoginActivity extends BaseActivity {
    @Bind(R.id.phone)
    AutoCompleteTextView mPhone;
    @Bind(R.id.password)
    EditText mPassword;
    @Bind(R.id.remember_phone)
    AppCompatCheckBox mRememberPhone;
    @Bind(R.id.remember_password)
    AppCompatCheckBox mRememberPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        String p = Settings.get(String.valueOf(mRememberPhone.getId()), null);
        String pw = Settings.get(String.valueOf(mRememberPassword.getId()), null);
        if (StringUtils.isEmpty(p)) {
            mRememberPhone.setChecked(false);
        } else {
            mRememberPhone.setChecked(true);
            mPhone.setText(p);
        }
        if (StringUtils.isEmpty(pw)) {
            mRememberPassword.setChecked(false);
        } else {
            mRememberPassword.setChecked(true);
            mPassword.setText(new String(Base64.decode(pw, Base64.DEFAULT)));
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.forget_password, R.id.sign_in_button, R.id.register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forget_password:
                startActivity(new Intent(this, ForgetPasswordActivity.class));
                break;
            case R.id.register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.sign_in_button:
                String mobile = mPhone.getText().toString();
                String password = mPassword.getText().toString();

                if (StringUtils.isEmpty(mobile)) {//电话号码为空
                    mPhone.setError(getString(R.string.error_phone_empty));
                } else if (!StringUtils.moreThanLength(mobile, 11)) {//手机号码位数不正确
                    mPhone.setError(getString(R.string.error_phone_length));
                } else if (StringUtils.isEmpty(password)) {
                    mPassword.setError(getString(R.string.error_password_empty));
                } else {
                    login(mobile, password);
                }

                break;
            default:
                break;
        }
    }

    private void login(final String mobile, final String password) {
        final ProgressDialogCompat progress = new ProgressDialogCompat(this);
        progress.show();
        LoginData data = new LoginData();
        data.setMobile(mobile);
        data.setPassword(MD5.md5(password).substring(0, 16).toUpperCase());
        progress.setMessage(getString(R.string.prompt_login_loading));
        Call<Result<User>> call = PalmRetrofit.getInstance().getApi().login(new Request<>(data));
        call.enqueue(new PalmCallBack<User>(this) {
            @Override
            public void succeed(User user) {
                if (!progress.isCanceled()) {
                    PalmSession.setSession(user);
                    if (mRememberPhone.isChecked())
                        Settings.put(String.valueOf(mRememberPhone.getId()), mobile);
                    if (mRememberPassword.isChecked())
                        Settings.put(String.valueOf(mRememberPassword.getId()), Base64.encodeToString(password.getBytes(), Base64.DEFAULT));
                    progress.dismiss();
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void failed(String message) {
                if (!progress.isCanceled()) {
                    progress.dismiss();
                    Toast.makeText(getContext(), StringUtils.isEmpty(message) ? getString(R.string.prompt_login_failed) : message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

